import json

from django.http import HttpResponse

from utils.http.response import json_response
from django.shortcuts import render

# Create your views here.
from django.views import View

from webcases.models import WebTestingCase, WebTestingCaseSteps
from webcases.utils.web_testing_utils.run_case import run_case


class WebProjectAdd(View):
    """添加web测试项目"""

    def post(self, request):
        pass


class WebProjectDelete(View):
    """删除web测试项目"""

    def post(self, request):
        pass


class WebProjectUpdate(View):
    """修改web测试项目"""

    def post(self, request):
        pass


class WebProjectSearch(View):
    """查找web测试项目"""

    def get(self, request):
        pass


class WebCasesAdd(View):
    """添加web测试用例"""

    def post(self, request):
        data = json.loads(request.body.decode())
        case = WebTestingCase(
            case_name=data['case_name'],
            case_desc=data['case_desc'],
            project_name=data['project_name'],
            browser=data['browser']
        )
        case.save()
        for step in data['steps']:
            case_step = WebTestingCaseSteps(
                step_sequence=step['step_sequence'],
                step_name=step['step_name'],
                step_order=step['step_order'],
                locate_by=step['locate_by'],
                locate_pattern=step['locate_pattern'],
                value=step['value'],
                case_name=case
            )
            case_step.save()
        return json_response(200, 'web测试用例添加成功')


class WebCasesDelete(View):
    """删除web测试用例"""

    def post(self, request):
        pass


class WebCasesUpdate(View):
    """修改web测试用例"""

    def post(self, request):
        pass


class WebCasesSearch(View):
    """查找web测试用例"""

    def get(self, request):
        pass


class WebCasesRun(View):
    """执行web测试用例"""

    def get(self, request, case_id):
        case = WebTestingCase.objects.get(id=case_id)
        steps = case.webtestingcasesteps_set.all()
        steps = sorted(steps, key=lambda x: x.step_sequence)
        for step in steps:
            print(step.step_name)
            print(step.step_order)
            print(step.locate_by)
        return HttpResponse(steps)
